package com.lhkj.ct.admin.modules.patient.controller;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.lhkj.ct.base.annntation.Log;
import com.lhkj.ct.base.constants.Constants;
import com.lhkj.ct.base.enums.ActionType;
import com.lhkj.ct.base.model.ro.ActionResult;
import com.lhkj.ct.base.utils.ShiroUtil;
import com.lhkj.ct.base.utils.file.excel.ExcelUtils;
import com.lhkj.ct.base.validator.group.ValGroups;
import com.lhkj.ct.meta.modules.patient.model.dto.ArchiveConsolidationDto;
import com.lhkj.ct.meta.modules.patient.model.dto.ImportPatientDto;
import com.lhkj.ct.meta.modules.patient.model.dto.PatientQuery;
import com.lhkj.ct.meta.modules.patient.model.entity.TblPatient;
import com.lhkj.ct.meta.modules.patient.model.vo.PatientForm;
import com.lhkj.ct.meta.modules.patient.model.vo.PatientPageVo;
import com.lhkj.ct.meta.modules.patient.service.ArchiveModuleProcess;
import com.lhkj.ct.meta.modules.patient.service.PatTagService;
import com.lhkj.ct.meta.modules.patient.service.PatientService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 档案表 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2023-09-17
 */
@RestController
@RequestMapping("api/plat/patient/manage")
@Api(tags = {"1.1.档案管理"})
@Validated
public class PatientController {

    @Resource
    private PatientService patientService;

    @Resource
    private PatTagService patTagService;

    @Resource
    private ArchiveModuleProcess archiveModuleProcess;

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "全部档案列表")
    @GetMapping("all")
    //@RequiresPermissions(value = {"system:patient:all"}, logical = Logical.OR)
    public ActionResult<IPage<PatientPageVo>> all(PatientQuery patientQuery) {
        return ActionResult.success(patientService.getUserPage(patientQuery));
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "个体档案列表")
    @GetMapping("personal")
    //@RequiresPermissions(value = {"system:patient:personal"}, logical = Logical.OR)
    public ActionResult<IPage<PatientPageVo>> personal(PatientQuery patientQuery) {
        patientQuery.setPatType(1);
        return ActionResult.success(patientService.getUserPage(patientQuery));
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "团体档案列表")
    @GetMapping("group")
    //@RequiresPermissions(value = {"system:patient:unit"}, logical = Logical.OR)
    public ActionResult<IPage<PatientPageVo>> group(PatientQuery patientQuery) {
        patientQuery.setPatType(2);
        return ActionResult.success(patientService.getUserPage(patientQuery));
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "档案详情")
    @GetMapping("{userId}")
    //@RequiresPermissions(value = {"system:patient:get"}, logical = Logical.OR)
    public ActionResult<PatientForm> details(@PathVariable String userId) {
        return ActionResult.success(patientService.getForm(userId));
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增档案")
    @PostMapping("insert")
    @Log(title = "档案管理", actionType = ActionType.INSERT)
    //@RequiresPermissions(value = {"system:patient:insert"}, logical = Logical.OR)
    public ActionResult<Void> insert(@Validated(value = {ValGroups.Insert.class}) @RequestBody PatientForm patientForm) {
        return ActionResult.judge(patientService.savePatient(patientForm));
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "修改档案基本信息")
    @PostMapping("update")
    @Log(title = "档案管理", actionType = ActionType.UPDATE)
    //@RequiresPermissions(value = {"system:patient:update", "system:patient:get"}, logical = Logical.OR)
    public ActionResult<Void> update(@Validated(value = {ValGroups.Update.class}) @RequestBody PatientForm patientForm) {
        return ActionResult.judge(patientService.savePatient(patientForm));
    }

    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "校验证件号码唯一性")
    @PostMapping("checkUnique")
    public ActionResult<Boolean> checkIdentNoUnique(@RequestBody TblPatient patient) {
        return ActionResult.success(patientService.checkIdentNoUnique(patient));
    }

    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "删除接口", notes = "支持批量删除")
    @DeleteMapping("delete")
    @Log(title = "档案管理", actionType = ActionType.DELETE)
    //@RequiresPermissions(value = {"system:patient:delete"}, logical = Logical.OR)
    public ActionResult<Void> delete(@RequestBody @NotEmpty(message = "删除的id不能为空") List<String> ids) {
        int count = patientService.removeByIds(ids);
        return ActionResult.success("删除完成，共删除【" + count + "】条");
    }

    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "档案已选标签")
    @GetMapping("tags")
    //@RequiresPermissions(value = {"system:patient:get"}, logical = Logical.OR)
    public ActionResult<List<String>> all(@RequestParam String patId) {
        return ActionResult.success(patTagService.getByPatId(patId));
    }

    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "保存标签")
    @PostMapping("{patId}/saveTags")
    @Log(title = "档案标签", actionType = ActionType.UPDATE)
    //@RequiresPermissions(value = {"system:patientTag:save"}, logical = Logical.OR)
    public ActionResult<Void> saveTags(@PathVariable String patId, @NotNull(message = "标签id不能为null") @RequestBody List<String> tagIds) {
        patientService.getBaseMapper().update(new LambdaUpdateWrapper<TblPatient>().set(TblPatient::getUpdateBy, ShiroUtil.getAuthUserInfo().getUserId()).eq(TblPatient::getId, patId));
        patTagService.save(patId, tagIds);
        return ActionResult.success();
    }

    @ApiOperationSupport(order = 10)
    @ApiOperation(value = "导出档案模板", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @PostMapping("exportModule")
    @Log(title = "档案模板", actionType = ActionType.EXPORT)
    //@RequiresPermissions(value = {"system:patientTag:save"}, logical = Logical.OR)
    public void exportModule() {
        Workbook sheets = archiveModuleProcess.generateTemplate();
        ExcelUtils.export(sheets, "档案模板");
    }

    @ApiOperationSupport(order = 11)
    @ApiOperation(value = "批量建档")
    @PostMapping("batchCreate")
    @Log(title = "档案管理", actionType = ActionType.IMPORT)
    //@RequiresPermissions(value = {"system:patientTag:save"}, logical = Logical.OR)
    public ActionResult<Void> batchCreate(@Validated @RequestBody ImportPatientDto importDto) {
        archiveModuleProcess.importArchives(importDto);
        return ActionResult.success();
    }

    @ApiOperationSupport(order = 12)
    @ApiOperation(value = "归档")
    @PostMapping("consolidation")
    @Log(title = "档案管理", actionType = ActionType.UPDATE)
    //@RequiresPermissions(value = {"system:patientTag:save"}, logical = Logical.OR)
    public ActionResult<Void> consolidation(@Validated @RequestBody ArchiveConsolidationDto importDto) {
        return ActionResult.judge(patientService.consolidation(importDto));
    }

    @ApiOperationSupport(order = 13)
    @ApiOperation(value = "扫码归档", hidden = true)
    @GetMapping("scan/consolidation")
    public void scanConsolidation(@RequestParam String unitId, HttpServletResponse response) throws IOException {
        UriComponentsBuilder redirectBuilder = UriComponentsBuilder.fromUriString(Constants.SERVICE_BASE_URL).path("/wechat/#/");
        redirectBuilder.queryParam("token", ShiroUtil.getSession().getId());
        String url = redirectBuilder.build().toUriString();
        response.sendRedirect(url);
    }
}
